package code.oldCode.feishuSpecializedTraining.binary_tree;

import utils.TreeNode;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @author 26029
 * @date 2025/3/13
 * @description
 */
public class MyBinaryTree4 {
    // 404. 左叶子之和
    public int sumOfLeftLeaves(TreeNode root) {
        if (root == null)
            return 0;
        int leftSum = 0, rightSum = 0;
        // 有左节点
        if (root.left != null) {
            // 如果左节点是叶子
            if (root.left.left == null && root.left.right == null) {
                leftSum = root.left.val;
            } else { // 左节点不是叶子，递归
                leftSum = sumOfLeftLeaves(root.left);
            }
        }
        // 有右节点
        if (root.right != null) {
            // 如果右节点不是叶子，递归
            if (!(root.right.left == null && root.right.right == null)) {
                rightSum = sumOfLeftLeaves(root.right);
            }
        }
        return leftSum + rightSum;
    }

    // 513. 找树左下角的值
    public int findBottomLeftValue(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int ans = 0;
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode treeNode = queue.poll();
                if (i == 0)
                    ans = treeNode.val;
                if (treeNode.left != null)
                    queue.offer(treeNode.left);
                if (treeNode.right != null)
                    queue.offer(treeNode.right);
            }
        }
        return ans;
    }

    // 112. 路径总和
    public boolean hasPathSum(TreeNode root, int targetSum) {
        if (root == null)
            return false;
        if (root.left == null && root.right == null)
            return root.val == targetSum;
        boolean left = hasPathSum(root.left, targetSum - root.val);
        boolean right = hasPathSum(root.right, targetSum - root.val);
        return left || right;
    }
}
